package com.example.myweb.Service.Auth.Impl;

import com.example.myweb.Domain.Entity.Article;
import com.example.myweb.Domain.Entity.Dynamic;

import com.example.myweb.Dto.AuthorInfoDTO;
import com.example.myweb.Dto.FeedItemDTO;
import com.example.myweb.Repository.JpaRepository.ArticleRepository;
import com.example.myweb.Repository.JpaRepository.DynamicRepository;
import com.example.myweb.Service.Auth.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private DynamicRepository dynamicRepository;

    @Override
    @Transactional(readOnly = true)
    public Page<FeedItemDTO> searchContent(String keyword, Pageable pageable) {
        // 分别从文章和动态中搜索
        Page<Article> articlePage = articleRepository.searchByKeyword(keyword, pageable);
        Page<Dynamic> dynamicPage = dynamicRepository.searchByKeyword(keyword, pageable);

        // 将搜索结果转换为统一的 FeedItemDTO
        List<FeedItemDTO> articles = articlePage.getContent().stream()
                .map(this::convertArticleToFeedItem)
                .collect(Collectors.toList());

        List<FeedItemDTO> dynamics = dynamicPage.getContent().stream()
                .map(this::convertDynamicToFeedItem)
                .collect(Collectors.toList());

        // 在内存中合并和排序
        List<FeedItemDTO> combinedList = new ArrayList<>();
        combinedList.addAll(articles);
        combinedList.addAll(dynamics);

        // 按发布时间倒序排序
        combinedList.sort(Comparator.comparing(FeedItemDTO::getPublishTime).reversed());

        // 手动进行分页
        int start = (int) pageable.getOffset();
        int end = Math.min((start + pageable.getPageSize()), combinedList.size());
        List<FeedItemDTO> pagedList = (start > combinedList.size()) ? List.of() : combinedList.subList(start, end);

        // 计算总数
        long total = articlePage.getTotalElements() + dynamicPage.getTotalElements();

        return new PageImpl<>(pagedList, pageable, total);
    }

    // --- 辅助转换方法 ---
    private FeedItemDTO convertArticleToFeedItem(Article article) {
        FeedItemDTO dto = new FeedItemDTO();
        dto.setType("article");
        dto.setId(article.getArticleId());
        dto.setTitle(article.getTitle());
        String content = article.getContent();
        dto.setSummary(content.substring(0, Math.min(content.length(), 150)) + "...");
        dto.setAuthor(new AuthorInfoDTO(article.getAuthor().getUserId(), article.getAuthor().getNickname(), article.getAuthor().getAvatarUrl()));
        dto.setPublishTime(article.getPublishTime());
        dto.setLikeCount(article.getLikeCount());
        dto.setCommentCount(article.getCommentCount());
        dto.setCoverImageUrl(article.getCoverImageUrl());
        return dto;
    }

    private FeedItemDTO convertDynamicToFeedItem(Dynamic dynamic) {
        FeedItemDTO dto = new FeedItemDTO();
        dto.setType("dynamic");
        dto.setId(dynamic.getDynamicId());
        dto.setSummary(dynamic.getContent());
        dto.setAuthor(new AuthorInfoDTO(dynamic.getAuthor().getUserId(), dynamic.getAuthor().getNickname(), dynamic.getAuthor().getAvatarUrl()));
        dto.setPublishTime(dynamic.getPublishTime());
        dto.setLikeCount(dynamic.getLikeCount());
        dto.setCommentCount(dynamic.getCommentCount());
        return dto;
    }
}